<?php

namespace addons\cmstostatic;

use app\common\library\Menu;
use think\Addons;
use think\Config;
use think\Db;

/**
 * 插件
 */
class Cmstostatic extends Addons
{
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name'    => 'cmstostatic',
                'title'   => '网站生成静态',
                'icon'    => 'fa fa-file-code-o',
                'sublist' => [
                    [
                        'name'    => 'cmstostatic/all',
                        'title'   => '一键操作',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/all', 'title' => '一键操作'],
                        ]
                    ],
                    [
                        'name'    => 'cmstostatic/home',
                        'title'   => '生成首页',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/home', 'title' => '生成首页'],
                        ]
                    ],
                    [
                        'name'    => 'cmstostatic/channel',
                        'title'   => '生成栏目',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/channel', 'title' => '生成栏目'],
                        ]
                    ],
                    [
                        'name'    => 'cmstostatic/article',
                        'title'   => '生成文章',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/article', 'title' => '生成文章'],
                        ]
                    ],
                    [
                        'name'    => 'cmstostatic/manage',
                        'title'   => '生成管理',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/manage', 'title' => '生成管理'],
                        ]
                    ],
                    [
                        'name'    => 'cmstostatic/config',
                        'title'   => '生成配置',
                        'icon'    => 'fa fa-table',
                        'sublist' => [
                            ['name' => 'cmstostatic/generate/config', 'title' => '生成配置'],
                        ]
                    ]
                ]
            ]
        ];
        Menu::create($menu);
        $this->synchronization();
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete("cmstostatic");
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable("cmstostatic");
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable("cmstostatic");
        return true;
    }

    public function appInit()
    {
        // 设定使用生成静态的标签库（复制cms）
        Config::set('template.taglib_pre_load', 'addons\\cmstostatic\\taglib\\Cms');
    }

    /**
     * 脚本替换
     */
    public function viewFilter(& $content)
    {
        $style = '';
        $script = '';
        $result = preg_replace_callback("/<(script|style)\s(data\-render=\"(script|style)\")([\s\S]*?)>([\s\S]*?)<\/(script|style)>/i", function ($match) use (&$style, &$script) {
            if (isset($match[1]) && in_array($match[1], ['style', 'script'])) {
                ${$match[1]} .= str_replace($match[2], '', $match[0]);
            }
            return '';
        }, $content);
        $content = preg_replace_callback('/^\s+(\{__STYLE__\}|\{__SCRIPT__\})\s+$/m', function ($matches) use ($style, $script) {
            return $matches[1] == '{__STYLE__}' ? $style : $script;
        }, $result ? $result : $content);
    }


    public function importSqlData()
    {
        $sqlFile = ADDON_PATH . 'cmstostatic' . DS . 'install.sql';
        if (is_file($sqlFile)) {
            $lines = file($sqlFile);
            $templine = '';
            foreach ($lines as $line) {
                if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
                    continue;
                }

                $templine .= $line;
                if (substr(trim($line), -1, 1) == ';') {
                    $templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);

                    try {
                        Db::execute($templine);
                    } catch (\Exception $e) {
                        $msg = $e->getMessage();
                        var_dump($msg);
                    }

                    $templine = '';
                }
            }
        }

        return true;
    }

    protected function synchronization()
    {
        $cmstostaticModel = new \addons\cmstostatic\model\Cmstostatic;
        $cmschannelModel = new \addons\cms\model\Channel;
        $cmstostaticMax = $cmstostaticModel->max('id');
        $cmschannelMax = $cmschannelModel->max('id');

        // 数据添加
        if($cmstostaticMax < $cmschannelMax){
            $cmstostaticDefault = [
                'isstatic' => '1',
                'dirname' => 'useless',
                'filename' => 'index.html',
                'indextype' => '0',
                'listtype' => 'list_{channel_id}_{page}.html',
                'showtype' => '{article_id}.html',
            ];

            for($i = $cmstostaticMax; $i < $cmschannelMax; $i++){
                $cmstostaticModel->data($cmstostaticDefault, true)->isUpdate(false)->save();
            }
        }

        // 数据更新
        $cmschannelSet = collection($cmschannelModel->order('id asc')->select())->toArray();
        $cmschannelRelation = [];
        foreach($cmschannelSet as $item){
            $cmschannelRelation[$item['id']] = $item;
        }

        $cmstostaticSet = collection($cmstostaticModel->order('id asc')->select())->toArray();
        $cmstostaticRelation = [];
        foreach($cmstostaticSet as $item){
            $cmstostaticRelation[$item['id']] = $item;
        }

        foreach($cmschannelSet as $cmschannel){
            // 新增更新
            $cmstostaticModel->where(['id'=>$cmschannel['id'], 'dirname'=>'useless'])->update(['dirname'=>$cmschannel['diyname']]);

            // 修改更新
            if(isset($cmstostaticRelation[$cmschannel['id']]) && $cmschannel['diyname'] != $cmstostaticRelation[$cmschannel['id']]['dirname']){
                $cmstostaticModel->where(['id'=>$cmschannel['id']])->update(['dirname'=>$cmschannel['diyname']]);
            }
        }

        // 数据删除 TODO 多余栏目数据可以不用删除，冗余在系统中不影响功能
        $cmstostaticModel->where(['dirname'=>'useless'])->delete();

        foreach($cmstostaticRelation as $cmstostatic){
            if(!isset($cmschannelRelation[$cmstostatic['id']])){
                $cmstostaticModel->where(['id'=>$cmstostatic['id']])->delete();
            }
        }

        return ['total'=>$cmstostaticModel->count('id')];
    }
}
